package com.west.xu.jdbc.controller;

import com.google.gson.GsonBuilder;
import com.west.xu.jdbc.domain.User;
import com.west.xu.jdbc.service.IDbService;
import com.west.xu.jdbc.service.IUserService;
import com.west.xu.jdbc.utils.JsonParseUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
public class UserController {
    private static final Logger LOG = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private IUserService userService;
    @Autowired
    private IDbService dbService;

    @RequestMapping(value = "/selectUser", method = RequestMethod.GET)
    @ApiOperation(value = "查询用户", notes = "查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "用户Id", dataType = "Long", required = true)
    })
    public User selectUser(@RequestParam Long id) {
        User user = userService.selectUser(id);
        LOG.info("tencent-jdbc -- response info: [" + new GsonBuilder().create().toJson(user) + "]");
        return user;
    }

    @RequestMapping(value = "/saveUser", method = RequestMethod.POST)
    @ApiOperation(value = "保存用户", notes = "保存用户信息")
    public User saveUser(@RequestBody User user) {
        user.setUserId(RandomStringUtils.randomAlphanumeric(20));
        int result = userService.saveUser(user);
        LOG.info("tencent-jdbc -- response info: [" + new GsonBuilder().create().toJson(user) + "]");
        return user;
    }


    @RequestMapping(value = "/importUser/{totalNum}/{bulkSize}", method = RequestMethod.GET)
    @ApiOperation(value = "导入用户", notes = "批量导入用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "totalNum", value = "用户总个数", dataType = "Long", required = true),
            @ApiImplicitParam(paramType = "path", name = "bulkSize", value = "最大批量入库数", dataType = "Long", required = true),
    })
    public String importUser(@PathVariable(name = "totalNum") Integer totalNum,
                             @PathVariable(name = "bulkSize") Integer bulkSize) throws InterruptedException {
        List<String> userJsonList = createUsers(totalNum);
        long start = System.currentTimeMillis();

        List<String> dataList = new ArrayList<>();
        for (int n = 0; n < userJsonList.size(); n++) {
            dataList.add(userJsonList.get(n));
            if (dataList.size() > 0
                    && dataList.size() % bulkSize == 0) {
                long st = System.currentTimeMillis();
                int res = userService.saveUsers(dataList);
                dataList = new ArrayList<>();
                long en = System.currentTimeMillis();
                LOG.info("Save Users Count ==>" + res + " |Cost ==>" + (en - st) + " ms");
            }
        }
        if (dataList.size() > 0) {
            long st = System.currentTimeMillis();
            int res = userService.saveUsers(dataList);
            long en = System.currentTimeMillis();
            LOG.info("Save Users Count ==>" + res + " |Cost ==>" + (en - st) + " ms");
        }

        long end = System.currentTimeMillis();
        String result = "Total Create User Count == " + userJsonList.size() + "|Cost== " + (end - start) + " ms";
        LOG.info(result);
        return result;
    }

    private List<String> createUsers(Integer totalNum) {

        List<String> userJsonList = new ArrayList<>();

        for (int n = 0; n < totalNum; n++) {
            User obj = new User();
            obj.setId(1L);
            obj.setName(RandomStringUtils.randomAlphabetic(10));
            obj.setUserId(RandomStringUtils.randomAlphanumeric(20));
            obj.setAge(30 + new Random().nextInt(10));
            obj.setSex(new Random().nextInt(2));
            userJsonList.add(JsonParseUtil.toJSONString(obj));
        }
        return userJsonList;
    }


    @RequestMapping(value = "/batchUpdae/{totalNum}/{split}", method = RequestMethod.GET)
    @ApiOperation(value = "批量更新", notes = "批量更新信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "totalNum", value = "执行记录数", dataType = "Long", required = true),
            @ApiImplicitParam(paramType = "path", name = "split", value = "split", dataType = "Long", required = true)
    })
    public String batchUpdate(@PathVariable(name = "totalNum") Integer totalNum,
                              @PathVariable(name = "split") Integer split) {

        return "result==" + dbService.batchUpdate(totalNum, split);
    }

    @RequestMapping(value = "/batchInsert/{totalNum}", method = RequestMethod.GET)
    @ApiOperation(value = "批量插入", notes = "批量插入信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "totalNum", value = "执行记录数", dataType = "Long", required = true)
    })
    public String batchInsert(@PathVariable(name = "totalNum") Integer totalNum) {

        return "result==" + dbService.batchInsert(totalNum);
    }
}
